package com.dd.ent.car.ui.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

/**
 * @author wangpeng
 * @since 2017年03月08日 上午11:41.
 */

public class BaseDialog extends Dialog {

    protected Context mCtx;

    protected Object mTag;

    public BaseDialog(Context context) {
        super(context);
        mCtx = context;
    }

    public BaseDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        mCtx = context;
    }

    public BaseDialog(Context context, int themeResId) {
        super(context, themeResId);
        mCtx = context;
    }

    @Override
    public void dismiss() {

        try {

            if (mCtx instanceof Activity) {
                Activity aty = (Activity) mCtx;
                boolean isFinishing = aty.isFinishing();
                if (!isFinishing) {
                    super.dismiss();
                }
            } else {
                if (isShowing()) {
                    super.dismiss();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void show(){
        try {
            Activity activity = this.getOwnerActivity();
            if (mCtx instanceof Activity) {
                activity = (Activity)mCtx;
            }
            if ( activity != null ){
                boolean isFinishing = activity.isFinishing();
                if (!isFinishing && activity.getWindow() != null) {
                    super.show();
                }
            }else{
                super.show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setTag(Object tag) {
        mTag = tag;
    }

    public Object getTag(){
        return mTag;
    }

    /**
     * 判断当前用户触摸是否超出了Dialog的显示区域
     *
     * @param context
     * @param event
     * @return
     */
    protected boolean isOutOfBounds(Context context, MotionEvent event) {
        final int x = (int) event.getX();
        final int y = (int) event.getY();
        final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
        final View decorView = getWindow().getDecorView();
        return (x < -slop) || (y < -slop) || (x > (decorView.getWidth() + slop))
                || (y > (decorView.getHeight() + slop));
    }


}
